

import UIKit
import GradientLoadingBar
import Alamofire
import Reachability
import SwiftEventBus


class CustomRoleViewController: UIViewController {
    let cell_identifier:String = "recommendRoleCell"
    var list:[Role] = []
    let reachability = try! Reachability()
    // 懒加载
    lazy var tableView : UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        
        let itemW = (UIScreen.main.bounds.width - 32)/2
        layout.itemSize = CGSize(width: itemW, height: itemW*3/4)
        
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 10
        
        layout.scrollDirection = .vertical // 竖向滑动
        
        
        let tableView = UICollectionView(frame: CGRectMake(0, 0, UIScreen.main.bounds.width, UIScreen.main.bounds.height-108), collectionViewLayout: layout)
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = primaryDarkBackgroundColor
        tableView.register(CustomRoleCell.self, forCellWithReuseIdentifier: cell_identifier)
        
        return tableView
    }()
    override var wx_titleTextAttributes: [NSAttributedString.Key : Any]? {
        return [NSAttributedString.Key.foregroundColor: UIColor.white]
    }
    private let gradientLoadingBar = NotchGradientLoadingBar(
        height: 3.0
    )
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "角色"
        gradientLoadingBar.fadeIn()
        self.view.addSubview(tableView)
        self.view.backgroundColor = primaryDarkBackgroundColor
        
        
        let createRoleButton = UIButton(type: .custom)
        createRoleButton.setTitle("创建角色", for: .normal)
        createRoleButton.layer.cornerRadius = 21
        createRoleButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
        createRoleButton.frame.size = CGSize(width: 68, height: 20)
        createRoleButton.backgroundColor = .primaryColor
        createRoleButton.addTarget(self, action: #selector(createRole(_:)), for: .touchUpInside)
        self.view.addSubview(createRoleButton)
        createRoleButton.snp.makeConstraints { make in
            make.centerX.equalTo(self.view)
            make.bottom.equalTo(self.bottomLayoutGuide.snp.top).offset(-16)
            make.height.equalTo(42)
            make.width.equalTo(UIScreen.main.bounds.width*2/3)
        }
        
        reachability.whenReachable = { reachability in
            if reachability.connection == .wifi {
                print("Reachable via WiFi")
            } else {
                print("Reachable via Cellular")
            }
            
            self.getLocalJson()
            
            self.getAllRoleList()
        }
        
        do {
            try reachability.startNotifier()
        } catch {
            print("Unable to start notifier")
        }
        
        SwiftEventBus.onMainThread(self, name: EVENT_NAME_DELETE_ROLE) { result in
            if let result = result{
                
                let alertController = UIAlertController(title: "提示",
                                        message: "确定要删除此角色吗？", preferredStyle: .alert)
                        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                        let okAction = UIAlertAction(title: "删除", style: .default, handler: {
                            action in
                            let deleteRole : Role = result.object as! Role
                            var index = 0
                            for role in self.list{
                                if role.title == deleteRole.title && role.description == deleteRole.description{
                                    break
                                }
                                index = index + 1
                            }
                            self.list.remove(at: index)
                            self.tableView.reloadData()
                            self.updateLocalJson()
                        })
                        alertController.addAction(cancelAction)
                        alertController.addAction(okAction)
                        self.present(alertController, animated: true, completion: nil)
                
            }
            
        }
        
        SwiftEventBus.onMainThread(self, name: EVENT_NAME_ADD_ROLE) { result in
            if let result = result{
                let addRole : Role = result.object as! Role
                
                self.list.append(addRole)
                self.tableView.reloadData()
                self.updateLocalJson()
            }
            
        }
        
    }
    
    func updateLocalJson(){
        do {
            var roleResponse = RoleResponse(code: 200, data: self.list, message: "success")
            let jsonEncoder = JSONEncoder()
            let jsonData = try jsonEncoder.encode(roleResponse)
            let json = String(data: jsonData, encoding: String.Encoding.utf8)
            if let jsonString = json{
                StoreManager.setRecommendRoleJson(json: jsonString)
            }
        } catch {
            print(error)
        }
    }
    
    @objc private func createRole(_ sender: Any) {
        
        let detailViewController = CreateRoleViewController()
        detailViewController.pageTitle = "创建角色"
        
        self.navigationController?.pushViewController(detailViewController, animated: true)
        
        print("handleRightBarButtonTapped")
    }
    
    func getLocalJson(){
        if let json = StoreManager.getRecommendRoleJson(), !json.contains("[]"){
            self.parseJson(json: json)
        }else{
            self.getRecommendRoleList()
        }
        
    }
    
    
    //只拉取数据保存
    func getAllRoleList(){
        let parameters = BasicParameters()
        AFManager.sharedInstance.manager.request("\(baseUrl)diy_ai/listV2",method: .post,parameters: parameters,encoder: URLEncodedFormParameterEncoder.default).responseString { response in
            
            if let string = response.value{
                print(string)
                StoreManager.setAllRoleJson(json: string)
            }
        }
        
    }
    
    func getRecommendRoleList(){
        let parameters = BasicParameters()
        AFManager.sharedInstance.manager.request("\(baseUrl)diy_recommend/listV2",method: .post,parameters: parameters,encoder: URLEncodedFormParameterEncoder.default).responseString { response in
            
            if let string = response.value{
                print(string)
                
                self.parseJson(json: string)
            }else{
                self.gradientLoadingBar.fadeOut()
            }
        }
        
    }
    
    func parseJson(json: String?){
        
        if let string = json{
            let data = Data(string.utf8)
            do {
                let jsonDecoder = JSONDecoder()
                let roleResponse = try jsonDecoder.decode(RoleResponse.self, from: data)
                if !roleResponse.data.isEmpty{
                    StoreManager.setRecommendRoleJson(json: string)
                    gradientLoadingBar.fadeOut()
                    list = roleResponse.data
                    self.tableView.reloadData()
                }
                
                
            } catch {
                
                print(error)
            }
        }
    }
    
}

extension CustomRoleViewController: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return list.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cell_identifier, for: indexPath) as! CustomRoleCell
        cell.bindViewModel(role:list[indexPath.row])
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.item + 1)
        let chatViewController = AdvancedExampleViewController()
        let role = list[indexPath.row]
        chatViewController.roleDescription = role.description
        chatViewController.pageTitle = role.title
        chatViewController.rolePrompt = role.prompt
        chatViewController.inputHint = role.title
        chatViewController.type = 1
//        chatViewController.example = ""
//        chatViewController.exampleAnswer = role.description
        self.navigationController?.pushViewController(chatViewController, animated: true)
    }
    
}
